package com.tywj.panda.customer.usercenter.center

import android.os.Bundle
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.tywj.panda.customer.common.entity.UserEntity
import com.tywj.panda.customer.common.event.UserEvent
import com.tywj.panda.customer.common.http.PDObjectCallback
import com.tywj.panda.customer.common.tool.PermissionTool
import com.tywj.panda.customer.common.tool.UpLOadFileTool
import com.tywj.panda.customer.common.view.base.MyBaseActivity
import com.tywj.lib.core.common.extension.loadRound
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.panda.customer.usercenter.R
import com.tywj.panda.customer.usercenter.api.UserCenterApi
import com.tywj.panda.customer.usercenter.cache.UserCenterCache
import com.tywj.panda.customer.usercenter.route.UserCenterRoute
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.api.widget.Widget
import kotlinx.android.synthetic.main.user_activity_center.*
import java.io.File

@Route(path = UserCenterRoute.USER_CENTER_INFO)
class UserCenterActivity : MyBaseActivity() {
    override fun getLayoutID(): Int = R.layout.user_activity_center

    private val chooseDialog = PhotoChooseDialog()

    private lateinit var avatarFile: File

    private lateinit var albumWidget: Widget

    private var mPortraitUrl = ""

    private var nickName = ""

    //是否初始化
    private fun isAvaFileInitialzed(): Boolean = ::avatarFile.isInitialized

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)

        UserCenterCache.userInfo?.let { showUserInfo(it) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))
        initWidget()
    }


    override fun initListener() {
        super.initListener()

        UserEvent.loadUserDataSuccessEvent.observe(this, Observer {
            loadUserInfo(it)
        })

        flPortrait.onClick {
            //TODO:接口待实现
//            chooseDialog.showDialog(supportFragmentManager)
        }

        chooseDialog.setonChoseListener {
            when (it) {
                PhotoChooseDialog.TYPE_TAKE_PHONE -> PermissionTool.camera { takePhoto() }

                PhotoChooseDialog.TYPE_FROM_ALBUM -> PermissionTool.storage { fromAlbum() }
            }
        }

        flNickName.onClick {
            UserCenterRoute.toNickName(nickName).navigation(this)
        }
    }

    private fun initWidget() {
        albumWidget = Widget.newDarkBuilder(this)
            .title(ResourcesUtil.getString(R.string.common_choose_picture))
            .toolBarColor(ResourcesUtil.getColor(R.color.common_bg_black))
            .statusBarColor(ResourcesUtil.getColor(R.color.common_bg_black))
            .build()
    }

    private fun showUserInfo(info: UserEntity) {

        tvNickName.text =
            if (info.nickName.isNullOrEmpty()) ResourcesUtil.getString(R.string.user_name_empty) else (info.nickName)

        tvUserId.text = info.uid
        tvPhone.text = info.phone

        info.avatar?.let {
            ivAvatar.loadRound(it, R.drawable.common_portrait_default)
        }

        nickName = info.nickName
    }


    private fun takePhoto() {
        Album.camera(this)
            .image()
            .onResult {
                showImage(it)

            }
            .start()
    }

    private fun fromAlbum() {
        Album.image(this)
            .multipleChoice()
            .selectCount(1)
            .columnCount(3)
            .camera(true)
            .widget(albumWidget)
            .onResult {
                showImage(it.first().path)
            }
            .start()
    }

    private fun showImage(path: String) {
        ivAvatar.loadRound(path, R.drawable.common_portrait_default)
        avatarFile = File(path)
    }

    private fun upLoadImageToAss() {

        if (isAvaFileInitialzed()) {
            UpLOadFileTool.uploadImage(UpLOadFileTool.TYPE_PORTRAIT, avatarFile, {
                LogUtil.e(it)
                saveUserInfo(it)
            }, {
                saveUserInfo(mPortraitUrl)
            })
        } else {
            //没有初始化说明，没有头像或没有选择头像
            saveUserInfo(mPortraitUrl)
        }
    }

    private fun saveUserInfo(url: String) {
        showLoadingDialog(R.string.common_loading)
    }

    private fun loadUserInfo(uid: String) {
        showLoadingDialog()

        UserCenterApi.getUserDetails(uid).attachToLifecycle(this)
            .execute(object : PDObjectCallback<UserEntity>(UserEntity::class.java) {
                override fun success(data: UserEntity) {
                    UserCenterCache.userInfo = data

                    showUserInfo(data)
                }

                override fun error(code: Int, message: String) {
                    super.error(code, message)
                    shortToast(message)
                }

                override fun onComplete() {
                    super.onComplete()
                    dismissLoadingDialog()
                }
            })
    }
}